// pages/foster-list/foster-list.js
const app = getApp();
const util = require('../../utils/util.js');

Page({
  data: {
    petType: '',
    petGender: '',
    publisher: '',
    fosterList: []
  },

  onLoad() {
    this.loadFosterList();
  },

  onShow() {
    // 从编辑页返回时刷新列表
    if (this.data.fosterList.length > 0) {
      this.loadFosterList();
    }
  },

  loadFosterList() {
    app.showLoading();
    const userInfo = wx.getStorageSync('userInfo');
    const params = {
      page: 1,
      size: 100,
      currentUserId: userInfo ? userInfo.id : null
    };
    
    if (this.data.petType) {
      params.petType = this.data.petType;
    }
    if (this.data.petGender) {
      params.petGender = this.data.petGender;
    }
    if (this.data.publisher) {
      params.publisher = this.data.publisher;
    }

    app.request({
      url: '/foster/user/list',
      method: 'GET',
      data: params
    }).then(res => {
      if (res.success) {
        const list = (res.data.records || []).map(item => ({
          ...item,
          image: this.getFirstImage(item.photos),
          isMyPost: userInfo && item.userId === userInfo.id,
          createTime: util.formatDateTime(item.createTime)
        }));
        this.setData({ fosterList: list });
      }
    }).catch(err => {
      app.showToast('加载失败');
      console.error(err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  getFirstImage(photos) {
    if (!photos) {
      return 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
    }
    const imageArray = photos.split(',');
    return imageArray[0] || 'https://img1.baidu.com/it/u=2531584226,2194794184&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500';
  },

  // 按宠物类型筛选
  filterByPetType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ petType: type });
    this.loadFosterList();
  },

  // 按性别筛选
  filterByGender(e) {
    const gender = e.currentTarget.dataset.gender;
    this.setData({ petGender: gender });
    this.loadFosterList();
  },

  // 按发布者筛选
  filterByPublisher(e) {
    const publisher = e.currentTarget.dataset.publisher;
    this.setData({ publisher: publisher });
    this.loadFosterList();
  },

  viewDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/foster-detail/foster-detail?id=${id}`
    });
  },

  // 编辑帖子
  editPost(e) {
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/foster-publish/foster-publish?id=${item.id}&mode=edit`
    });
  },

  goPublish() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }
    wx.navigateTo({
      url: '/pages/foster-publish/foster-publish'
    });
  }
});


